package msg

import (
	"context"
	"database/sql"
	"errors"
	"fmt"
	"git.mycaigou.com/gfyx/common/tenant_db"
	"git.mycaigou.com/gfyx/micro-gfyx-oppty-service/infrastructure/common/errcode"
	"git.mycaigou.com/gfyx/micro-gfyx-oppty-service/infrastructure/common/utils"
	baseMsg "git.mycaigou.com/gfyx/micro-gfyx-oppty-service/infrastructure/repository/base/msg"
	"git.mycaigou.com/gfyx/micro-gfyx-oppty-service/infrastructure/repository/base/user"
	basePb "git.mycaigou.com/gfyx/micro-gfyx-oppty-service/proto/micro_gfyx_oppty_service_proto/micro-gfyx-oppty-service/base"
	"git.myscrm.cn/golang/stark/v4"
	"strconv"
	"time"
)

type msgService struct {
	msgRepo  baseMsg.MsgRepositoryIface
	userRepo user.UserRepositoryIface
}

// NewMsgService 构造函数
func NewMsgService(msgRepo baseMsg.MsgRepositoryIface, userRepo user.UserRepositoryIface) MsgServiceIface {
	return &msgService{
		msgRepo:  msgRepo,
		userRepo: userRepo,
	}
}

// List 消息列表
func (s *msgService) List(ctx context.Context, req *basePb.MsgListRequest) ([]*baseMsg.GfyxMessageInboxPo, *utils.PageInfo, error) {
	list := make([]*baseMsg.GfyxMessageInboxPo, 0)
	msgList, pageInfo, err := s.msgRepo.List(ctx, req)
	if err != nil {
		return list, pageInfo, err
	}
	return msgList, pageInfo, nil
}

func (s *msgService) GetReadStatusGroupSummary(ctx context.Context, isReaded int64) (int64, error) {
	return s.msgRepo.GetReadStatusGroupSummary(ctx, isReaded)
}

func (s *msgService) SetReaded(ctx context.Context, req *basePb.MsgSetReadedRequest) (int64, error) {
	id, err := s.msgRepo.SetReaded(ctx, req)
	return id, err
}

func (s *msgService) PushSiteMsg(ctx context.Context, req *basePb.SiteMessageRequest) error {
	//消息类型转换
	messageTypeVal := req.MessageType
	messageType := s.getMessageTypeName(messageTypeVal)
	//pb转po
	data := &baseMsg.GfyxMessageInboxPo{
		MessageType:  messageType,
		Title:        req.Title,
		Content:      req.Content,
		SenderId:     req.SenderId,
		ReceiverId:   req.ReceiverId,
		IsReaded:     2,
		ReceivedTime: time.Now(),
		ReadedTime:   sql.NullTime{},
		Link:         req.Link,
		CreatedBy:    strconv.FormatInt(req.SenderId, 10),
		CreatedOn:    time.Now(),
		ModifiedBy:   strconv.FormatInt(req.SenderId, 10),
		ModifiedOn:   time.Now(),
		IsDeleted:    0,
	}
	// 校验接收用户是否存在
	userInfo, err := s.userRepo.UserDetailByUserId(ctx, req.ReceiverId)
	if err != nil {
		stark.Logger.Errorf(ctx, "校验接收用户是否存在失败，error: %+v", err)
		return err
	} else if userInfo == nil || userInfo.Id == 0 {
		stark.Logger.Warnf(ctx, "用户不存在，userId:%d", req.ReceiverId)
		return errcode.UserNotExist
	}

	err = s.msgRepo.PushSiteMsg(ctx, data)
	if err != nil {
		stark.Logger.Errorf(ctx, "站内信推送失败，error: %+v", err)
		return err
	}
	return nil
}

func (s *msgService) BatchPushSiteMsg(ctx context.Context, req *basePb.BatchSiteMessageRequest) error {
	messageList := req.List
	tenantCode, err := tenant_db.GetTenantCode(ctx)
	if err != nil {
		stark.Logger.Errorf(ctx, "tenant_code获取失败, error:%+v", err)
		return errors.New("tenant_code获取失败")
	}
	messageInboxList := make([]*baseMsg.GfyxMessageInboxPo, 0)
	for _, msg := range messageList {
		if msg.Title == "" {
			return errors.New("title为空")
		}
		if msg.Content == "" {
			return errors.New("content为空")
		}
		if msg.ReceiverId == 0 {
			return errors.New("receiver_id为空")
		}
		if msg.TenantCode == "" {
			return errors.New("tenant_code为空")
		}
		if tenantCode != msg.TenantCode {
			fmt.Println("tenant_code1:", tenantCode, "tenant2:", msg.TenantCode)
			return errors.New("tenant_code与推送数据不一致")
		}

		// 校验接收用户是否存在
		userInfo, err := s.userRepo.UserDetailByUserId(ctx, msg.ReceiverId)
		if err != nil {
			return err
		} else if userInfo == nil || userInfo.Id == 0 {
			return errcode.UserNotExist
		}

		messageTypeVal := msg.MessageType
		messageType := s.getMessageTypeName(messageTypeVal)
		data := &baseMsg.GfyxMessageInboxPo{
			MessageType:  messageType,
			Title:        msg.Title,
			Content:      msg.Content,
			SenderId:     msg.SenderId,
			ReceiverId:   msg.ReceiverId,
			IsReaded:     2,
			ReceivedTime: time.Now(),
			ReadedTime:   sql.NullTime{},
			Link:         msg.Link,
			CreatedBy:    strconv.FormatInt(msg.SenderId, 10),
			CreatedOn:    time.Now(),
			ModifiedBy:   strconv.FormatInt(msg.SenderId, 10),
			ModifiedOn:   time.Now(),
			IsDeleted:    0,
		}
		messageInboxList = append(messageInboxList, data)
	}

	err = s.msgRepo.BatchPushSiteMsg(ctx, messageInboxList)
	if err != nil {
		stark.Logger.Errorf(ctx, "批量推送站内信失败，error: %+v", err)
		return err
	}

	return nil
}

func (s *msgService) getMessageTypeName(messageTypeVal basePb.MySiteMessageType) string {
	messageType := ""
	switch messageTypeVal {
	case basePb.MySiteMessageType_CLUE_REPORT:
		messageType = "线索报备"
	case basePb.MySiteMessageType_CUSTOMER_DYNAMIC:
		messageType = "客户动态"
	case basePb.MySiteMessageType_CUSTOMER_ALLOCATION:
		messageType = "客户分配"
	case basePb.MySiteMessageType_BUSINESS_SUBSCRIBE:
		messageType = "商机订阅"
	case basePb.MySiteMessageType_CLUE_SUBSCRIBE:
		messageType = "线索订阅"
	case basePb.MySiteMessageType_CUSTOMER_CHANGE:
		messageType = "客户变动"
	case basePb.MySiteMessageType_PROJECT_SUBSCRIBE:
		messageType = "项目订阅"
	case basePb.MySiteMessageType_EMPTY:
		messageType = ""
	}
	return messageType
}
